﻿using SaaS.Core;
using SaaS.Model.Enums;
using XCore.Logger;
using XCore.Extensions;
using XCore.Helper;
using XCore.Dependency;
using SaaS.Model.Entity.Systems;

namespace Web.System.Utils
{
    public class SystemLogger : LoggerBase, ISingletonDependency
    {
        private SystemSession Session { get; }
        public SystemLogger(SystemSession session) : base(CoreSetting.DefaultConnectionString, typeof(SystemAdminLog).GetTableName())
        {
            Session = session;
        }
        public bool Log<T>(int adminId, int targetId, string message, T value, SystemLoggerSource source)
        {
            LoggerInfo ei = new LoggerInfo
            {
                Message = message
            };
            ei.Properties["Source"] = (byte)source;
            ei.Properties["TargetId"] = targetId;
            ei.Properties["AdminId"] = adminId;
            ei.Properties["CustomData"] = value == null ? string.Empty : value.ToJson();
            ei.Properties["IP"] = HttpContext.GetIp();
            ei.Properties["Type"] = (byte)HttpContext.GetOperatingType();
            ei.Properties["Duration"] = StopwatchHelper.Milliseconds;
            ei.Properties["RequestInfo"] = HttpContext.GetRequestInfo();
            base.DbLog(ei);
            return true;
        }
        public bool Log<T>(int adminId, string message, T model, SystemLoggerSource source)
        {
            return Log(adminId, 0, message, model, source);
        }
        public bool Log(int adminId, int targetId, string message, SystemLoggerSource source)
        {
            return Log<string>(adminId, targetId, message, null, source);
        }
        public bool Log(int targetId, string message, SystemLoggerSource source)
        {
            return Log<string>(Session.AdminId, targetId, message, null, source);
        }
        public bool Log(string message, SystemLoggerSource source)
        {
            return Log(0, message, source);
        }
        public bool Log(int targetId, string message)
        {
            return Log(targetId, message, SystemLoggerSource.None);
        }
        public bool Log(string message)
        {
            return Log(0, message);
        }
    }
}
